﻿using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Util;
using EFCore.Sharding;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Api
{
    public static class InitJobExtentions
    {


        public static void InitStartJob(this IServiceCollection services)
        {
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            IDbAccessor db = serviceProvider.GetService<IDbAccessor>();
            IQueryable<Base_Job> base_Jobs = db.GetIQueryable<Base_Job>();
            List<Base_Job> jobs = base_Jobs.Where(t => t.State == "Y").ToList();
            if (jobs.Count > 0)
            {
                try
                {
                    jobs.ForEach(job =>
                    {
                        Type type = null;
                        GlobalAssemblies.AllTypes.ForEach(t =>
                        {
                            if (t.FullName==job.ClassName)
                            {
                                type = t;
                                // 使用反射创建类的实例
                                IJob_Business instance = (IJob_Business)Activator.CreateInstance(type);
                                //循环执行任务
                                if (job.Unit == "Date")
                                {
                                    string[] strings = job.StartTime.Split(":");
                                    JobHelper.SetDailyJob(instance.Job, Convert.ToInt32(strings[0]), Convert.ToInt32(strings[1]), 0, job.ClassName);
                                }
                                else 
                                {
                                    JobHelper.SetIntervalJob(instance.Job, job.Unit.ToTimeSpan(job.TimeSpan), job.ClassName);
                                }
                                
                                Console.WriteLine($"{DateTime.Now}:{job.ClassName}任务启动成功......");
                            }

                        });
                        
                    });
                }
                catch (Exception ex)
                {

                }
            }
        }

    }


}
